/*
 * @Author: 谢子健 1075010289@qq.com
 * @Date: 2024-10-22 21:42:41
 * @LastEditors: 谢子健 1075010289@qq.com
 * @LastEditTime: 2024-11-13 12:21:26
 * @FilePath: \ilink-vue-frontend\src\api\study\ossApi.ts
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
// ossApi.ts
import { api } from '@/api/api'; // 假设有封装好的 API 模块用于发送请求
import OSS from 'ali-oss';
import { nanoid } from 'nanoid';
// 阿里云 OSS 配置
const client = new OSS({
  region: 'oss-cn-beijing',
  accessKeyId: 'LTAI5tCCTsonpzgbA5od9dX1',
  accessKeySecret: 'Yxo3DXuIqm0DsZ4cIlNNlw4ssan4Jd',
  bucket: 'study-square',
});

export const uploadImageToOSS = async (file: File) => {
  try {
    // 获取用户的 userId
    const userInfoResponse = await api.get('/java/user/whoami_frontend');
    const userId = userInfoResponse.data.userId;
    if (!userId)
      throw new Error('未找到用户ID');

    // 使用雪花算法或其他唯一ID生成文件名
    const uniqueFileName = `note_picture/${userId}/${nanoid()}.${file.name.split('.').pop()}`;

    // 创建 FormData 对象
    const formData = new FormData();
    formData.append('file', file); // 添加文件
    formData.append('bucketName', 'study-square-migrate'); // 替换为实际的 bucketName
    formData.append('objectName', uniqueFileName); // 使用生成的文件名作为 objectName

    // 上传文件到 OSS，生成签名 URL
    const response = await api.post('/java/ground/study/course/uploadAndGetUrl', formData, {
      headers: {
        'Content-Type': 'multipart/form-data', // 设置请求头为 multipart/form-data
      },
    });

    // 返回签名的访问 URL
    return {
      url: response.data,
    };
  }
  catch (error) {
    console.error('上传文件到 OSS 失败:', error);
    throw new Error('上传文件到 OSS 失败，请检查配置或网络连接。');
  }
};

// 获取笔记内容的函数
export const getNoteContent = async (courseId: string, sourceId: string, resourceType: string) => {
  try {
    const response = await api.post('/java/ground/study/course/get_note', {
      sourceId,
      type: resourceType,
      noteContent: '',
      courseId,
    });
    return response.data;
  }
  catch (error) {
    console.error('获取笔记内容失败:', error);
    throw new Error('获取笔记内容失败');
  }
};

// 保存笔记内容的函数
export const saveNoteContent = async (courseId: string, sourceId: string, noteContent: string, resourceType: string) => {
  try {
    const response = await api.post('/java/ground/study/course/save_note', {
      sourceId,
      type: resourceType,
      noteContent,
      courseId,
    });
    return response.data;
  }
  catch (error) {
    console.error('保存笔记失败:', error);
    throw new Error('保存笔记失败');
  }
};

export { client };
